package com.ibm.risk.irmp.common.rest;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.ibm.risk.irmp.common.exception.AuthenticationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler({AuthenticationException.class})
    public ProblemDetail handle1(AuthenticationException e) {
        log.error("Error:", e);
        HttpStatus status = HttpStatus.UNAUTHORIZED;
        ProblemDetail detail = ProblemDetail.forStatusAndDetail(status, e.getMessage());
        return detail;
    }
    // 当发生异常后直接返回ProblemDetail对象
    @ExceptionHandler({Exception.class})
    public ProblemDetail handle2(Exception e) {
        log.error("Error:", e);
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        if (e instanceof AuthenticationException || e instanceof JWTVerificationException) {
            status = HttpStatus.UNAUTHORIZED;
        }
        ProblemDetail detail = ProblemDetail.forStatusAndDetail(status, e.getMessage());
        return detail;
    }
}
